local basic = require("luaScript.module.common.basic");
local redisOp = require("luaScript.redis.RedisOperator");

local clientIp = basic.getClientIP();
if clientIp ~= nil then
    basic.log("ClientIP:"..clientIp);
end

-- 获取共享内存black_ip_list
local black_ip_list = ngx.shared.black_ip_list;

-- 判断有没有过期
local lastUpdateTime = black_ip_list:get("last_update_time");
if lastUpdateTime ~= nil then
    local dif = ngx.now() - lastUpdateTime;
    if dif < 60 then
        -- 没有过期
        if black_ip_list:get(clientIp) then
            -- 直接403
            return ngx.exit(ngx.HTTP_FORBIDDEN);
        end
        return;
    end
end

local KEY = "limit:ip:blacklist";
-- 定时刷新
local redis = redisOp:new();
redis:open();
local ip_blacklist = redis:getSmembers(KEY);
redis:close();
if not ip_blacklist then
    basic.log("black ip set  is null");
    return;
else
    black_ip_list:flush_all();
    for i, v in ipairs(ip_blacklist) do
        black_ip_list:set(v, true);
    end
    --设置本地缓存的最新更新时间
    black_ip_list:set("last_update_time",ngx.now());
end

-- 刷新完毕之后再次判断
if black_ip_list:get(clientIp) then
    ngx.exit(ngx.HTTP_FORBIDDEN);
    return;
end